package com.yinlei.appserver

import android.content.Context
import java.io.PrintStream
import java.io.PrintWriter

/**
 * 内置的静态网页
 * assets中放置网页文件
 * 然后http://xxx:8088/static/a/b.html -> 映射为 assets/a/b.html
 */
class ResourceInAssetsHandler(val context: Context) : IResourceUriHandler {
    private var acceptPrefix = "/static/"

    override fun accept(url: String) = url.startsWith(acceptPrefix)

    override fun handle(url: String, httpContext: HttpContext) {
//        with(PrintWriter(nos)) {
//            println("HTTP/1.1 200 OK")
//            println()
//            println("from resource in assets handler")
//            flush()
//        }
        val startIndex = acceptPrefix.length
        val assetsPath = url.substring(startIndex)
        val fis = context.assets.open(assetsPath)
        val raw = StreamToolkit.readRawFromStream(fis)
        fis.close()
        val nos = httpContext.getUnderlySocket().getOutputStream()
        with(PrintStream(nos)) {
            println("HTTP/1.1 200 OK")
            println("Content-Length:${raw.size}")
            if (assetsPath.endsWith(".html")) {
                println("Content-Type:text/html")
            } else if(assetsPath.endsWith(".js")) {
                println("Content-Type:text/js")
            } else if(assetsPath.endsWith(".css")) {
                println("Content-Type:text/css")
            } else if(assetsPath.endsWith(".jpg")) {
                println("Content-Type:text/jpg")
            }
            println()
            write(raw) // body-response
        }
    }

}